package rui.game.component;

import lombok.Getter;
import rui.game.Chunk;

import java.util.*;
import java.util.stream.Collectors;

import static java.util.stream.IntStream.range;
import static rui.game.Chunk.toPosition;

/**
 * @author 赵睿
 */
@Getter
public class GamePanel {

    private Map<Double, Chunk> chunkMap = new HashMap<>();

    private List<Chunk> leftList=new ArrayList<>();
    private List<Chunk> rightList=new ArrayList<>();
    private List<Chunk> upList=new ArrayList<>();
    private List<Chunk> downList=new ArrayList<>();

    private int rowNum;
    private int columnNum;

    public GamePanel() {
        this(4, 4);
    }

    public static GamePanel init(GamePanel gamePanel) {
        if (gamePanel == null) {
            gamePanel = new GamePanel();
        }
        return gamePanel;
    }


    public GamePanel(int rowNum, int columnNum) {
        if(rowNum<=0){
            throw new NoSuchElementException("rowNum 为 "+rowNum);
        }

        if(columnNum<=0){
            throw new NoSuchElementException("columnNum 为 "+columnNum);
        }
        this.rowNum=rowNum;
        this.columnNum=columnNum;

        for (int i = 0; i < rowNum; i++) {
            for (int j = 0; j < columnNum; j++) {
                double position = toPosition(i, j);
                chunkMap.put(position, new Chunk(i, j));
            }
        }

        for (int i = 0; i < rowNum; i++) {
            for (int j = 0; j < columnNum; j++) {
                Chunk chunk = chunkMap.get(toPosition(i, j));
                Chunk left = chunkMap.get(toPosition(i - 1, j));
                Chunk right = chunkMap.get(toPosition(i + 1, j));
                Chunk up = chunkMap.get(toPosition(i, j - 1));
                Chunk down = chunkMap.get(toPosition(i, j + 1));
                chunk.nextTo(left, right, up, down);
            }
        }

        range(0,rowNum).forEach(value -> {
            upList.add(chunkMap.get(toPosition(value,0)));
            downList.add(chunkMap.get(toPosition(value,columnNum)));
        });

        range(0,columnNum).forEach(value -> {
            leftList.add(chunkMap.get(toPosition(rowNum,value)));
            downList.add(chunkMap.get(toPosition(0,value)));
        });

    }


    public List<Chunk> toList() {
        return chunkMap.entrySet().stream()
                .map(Map.Entry::getValue)
                .collect(Collectors.toList());
    }

    public void refresh() {
        chunkMap.entrySet().stream()
                .map(Map.Entry::getValue)
                .forEach(chunk -> chunk.setText(""));
    }
}
